﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using exsportance.Silverlight.Common.Utils;
using System.Collections.Generic;

namespace exsportance.Silverlight.Validate.Validators
{
    /// <summary>
    /// Validator for required minimum and/or maximun length
    /// </summary>
    public class StringLengthValidator : BaseValidator
    {

        #region members
        /// <summary>
        /// Validation failure message key for when the value is too short
        /// </summary>
        private const string TOO_SHORT = "stringLengthTooShort";

        /// <summary>
        /// Validation failure message key for when the value is too long
        /// </summary>
        private const string TOO_LONG = "stringLengthTooLong";

        protected Dictionary<string, string> _messagesTemplates = new Dictionary<string, string>(){
        {StringLengthValidator.TOO_SHORT,"'%value%' is less than %min% characters long"},
        {StringLengthValidator.TOO_LONG,"'%value%' is greater than %max% characters long"},
        };

        #endregion

        #region properties
        public int Min { get; set; }
        public int Max { get; set; }
        #endregion

        #region constructor
        public StringLengthValidator(int minLength)
            : base()
        {
            if (minLength <= 0)
                throw new ArgumentException("MinLength have to be greater than zero!", "minLength");

            Min = minLength;
        }

        public StringLengthValidator(int minLength, int maxLength)
            : this(minLength)
        {
            if (maxLength < minLength)
                throw new ArgumentException("MaxLength have to be greater than MinLength!", "maxLength");

            Max = maxLength;
        }
        #endregion

        #region protected methods
        protected override bool CheckValid(object value)
        {
            string valueString = value as string;

            rememberValue(valueString);

            int length = valueString != null ? valueString.Length : 0;


            if (length < Min)
            {
                raiseMessage(StringLengthValidator.TOO_SHORT);
                return false;
            }
            else
                if (length > Max && Max > 0)
                {
                    raiseMessage(StringLengthValidator.TOO_LONG);
                    return false;
                }


            return true;
        }

        protected override System.Collections.Generic.Dictionary<string, string> getMessageTemplates()
        {
            return _messagesTemplates;
        }
        #endregion
    }
}
